package com.wash.shoes.domain.dy.request;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.wash.shoes.domain.dy.model.*;
import com.wash.shoes.entity.BrandPo;
import com.wash.shoes.entity.ShopGoodsPo;
import com.wash.shoes.entity.ShopPo;
import com.wash.shoes.oss.ConstantProperties;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Component;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author lijianguo
 * @Date 29/03/2025 08:08
 * https://developer.open-douyin.com/docs/resource/zh-CN/local-life/develop/OpenAPI/general-capabilities/goods/save
 * 开发/OpenAPI/通用接口/商品发布/ 商品发布 1-免审修改商品接口 2-上下架商品 3-创建/更新商品接口 4-同步库存 5-创建/更新多SKU商品的SKU列表 6-创建适用人群 7-商品状态变更通知
 **/
@Log4j2
@Component
public class DyGoodsRequest extends DyBaseRequest {

    /**
     * @param shopGoodsPo 保存商品到抖音平台
     */
    public void saveOrUpdateProduct(ShopGoodsPo shopGoodsPo) {
        // 抖音的商品信息
        if (shopGoodsPo.getSellType().equals("3")) {
            Map<String, String> map = productAttrMapInit(shopGoodsPo);
            pushProductToDy(shopGoodsPo, map);
        } else {
            log.info("不是抖音的商品");
        }
    }

    /**
     * @param shopGoodsPo
     * @return 商品的属性
     */
    public Map<String, String> productAttrMapInit(ShopGoodsPo shopGoodsPo) {

        Map<String, String> productAttrMap = new HashMap<>();
        // APPOINTMENT 信息 预约信息
        AppointmentStruct appointmentStruct = new AppointmentStruct();
        appointmentStruct.setNeed_appointment(true);
        appointmentStruct.setAhead_time_type(1);
        appointmentStruct.setAhead_hour_num(1);
        appointmentStruct.setAhead_day_num(1);
        productAttrMap.put("appointment", JSONObject.toJSONString(appointmentStruct));
        productAttrMap.put("auto_renew", "true");
        CanNoUseDateStruct canNoUseDateStruct = new CanNoUseDateStruct();
        canNoUseDateStruct.setEnable(false);
        productAttrMap.put("can_no_use_date", JSONObject.toJSONString(canNoUseDateStruct));

        productAttrMap.put("Description", JSONObject.toJSONString(Collections.singletonList(shopGoodsPo.getName())));
        JSONArray image_list = new JSONArray();

        List<String> allIMg = getAllImgList(shopGoodsPo);
        for (String img : allIMg) {
            JSONObject image = new JSONObject();
            image.put("url", img);
            image_list.add(image);
        }
        productAttrMap.put("image_list", image_list.toJSONString());

        LimitUseRuleStruct limitUseRuleStruct = new LimitUseRuleStruct();
        limitUseRuleStruct.setIs_limit_use(true);
        limitUseRuleStruct.setUse_num_per_consume(10);
        productAttrMap.put("limit_use_rule", JSONObject.toJSONString(limitUseRuleStruct));

        NotificationStruct notificationStruct = new NotificationStruct();
        notificationStruct.setTitle("洗鞋洗衣卷使用规则");
        notificationStruct.setContent("衣服和鞋子均可以使用");
        productAttrMap.put("Notification", JSONObject.toJSONString(Collections.singletonList(notificationStruct)));
        // 1-允许退款 2-不可退款 3-有条件退
        productAttrMap.put("RefundPolicy", "1");
        // 1-不限制 2-仅直播间可见
        productAttrMap.put("show_channel", "1");
        // 可以享受店内其他优惠
        productAttrMap.put("superimposed_discounts", "true");
        // 使用人数限制
        UserNumLimitStruct userNumLimitStruct = new UserNumLimitStruct();
        userNumLimitStruct.setEnable_limit(true);
        userNumLimitStruct.setLimit_num(1);
        productAttrMap.put("user_num_limit", JSONObject.toJSONString(userNumLimitStruct));
        // 使用日期
        UseDateStruct useDateStruct = new UseDateStruct();
        useDateStruct.setUse_date_type(2);
        useDateStruct.setDay_duration(1);
        productAttrMap.put("use_date", JSONObject.toJSONString(useDateStruct));
        // 使用时间
        UseTimeStruct useTimeStruct = new UseTimeStruct();
        useTimeStruct.setUse_time_type(1);
        productAttrMap.put("use_time", JSONObject.toJSONString(useTimeStruct));
        // 退款是否需商家审核,目前设置不需要审核
        productAttrMap.put("refund_need_merchant_confirm", "false");
        return productAttrMap;
    }

    private List<String> getAllImgList(ShopGoodsPo shopGoodsPo) {
        List<String> imgList = new ArrayList<>();
        if (StrUtil.isNotBlank(shopGoodsPo.getUrl())) {
            List<String> result = Arrays.stream(shopGoodsPo.getUrl().split(","))
                    .map(s -> ConstantProperties.BASEURL + "/" + s).collect(Collectors.toList());
            imgList.addAll(result);
        }
        if (StrUtil.isNotBlank(shopGoodsPo.getBannerUrl())) {
            List<String> result = Arrays.stream(shopGoodsPo.getBannerUrl().split(","))
                    .map(s -> ConstantProperties.BASEURL + "/" + s).collect(Collectors.toList());
            imgList.addAll(result);
        }
        if (StrUtil.isNotBlank(shopGoodsPo.getDetailUrl())) {
            List<String> result = Arrays.stream(shopGoodsPo.getDetailUrl().split(","))
                    .map(s -> ConstantProperties.BASEURL + "/" + s).collect(Collectors.toList());
            imgList.addAll(result);
        }
        // 封面图只有2,5张
        if (imgList.size() >= 5) {
            imgList = imgList.subList(0, 5);
        }
        return imgList;
    }

    /**
     * 推送商品的Id到抖音的平台
     *
     * @param shopGoodsPo 商品的Id
     */
    public void pushProductToDy(ShopGoodsPo shopGoodsPo, Map<String, String> productAttrMap) {
        ShopPo shopPo = shopService.getById(shopGoodsPo.getShopId());
        Assert.notNull(shopPo, "店铺不存在,shopId:" + shopGoodsPo.getShopId());
        // TODO 根据品牌id获取品牌的配置信息
        BrandPo brandPo = brandService.getById(shopPo.getBrandId());
        // 根据品牌id获取抖音的poId
        List<String> poIdList = shopService.getAllDyPoidWithBrandId(shopPo.getBrandId());
        Assert.notEmpty(poIdList, "抖音的poId为空,请检查抖音的配置信息");
        /*        shopService.page(new Page<>(1, 10), new LambdaQueryWrapper<>());
        shopService.list(new LambdaQueryWrapper<>().eq(ShopPo::getBrandId, shopPo.getBrandId).last("limit 10"));*/

        SaveProductModel saveProductModel = new SaveProductModel();
        saveProductModel.setProduct_id(shopGoodsPo.getId());
        saveProductModel.setOut_id(shopGoodsPo.getId());
        saveProductModel.setProduct_name(shopGoodsPo.getName());
        saveProductModel.setCategory_full_name("洗涤护理-到家");
        saveProductModel.setCategory_id(Integer.parseInt(DyConstant.CATEGORY_ID));
        saveProductModel.setProduct_type(Integer.parseInt(DyConstant.PRODUCT_TYPE));
        saveProductModel.setProduct_sub_type(null);
        saveProductModel.setBiz_line(5);
        // 修改多品牌的时候注释掉
        // saveProductModel.setAccount_name("四川童摇信息科技有限公司");
        // saveProductModel.setTelephone(Collections.singletonList("15982021661"));
        saveProductModel.setAccount_name(brandPo.getCompany());

        saveProductModel.setTelephone(Collections.singletonList(brandPo.getPhone()));

        saveProductModel.setSold_start_time(System.currentTimeMillis() / 1000);
        saveProductModel.setSold_end_time(System.currentTimeMillis() / 1000 + 3600 * 24 * 365);
        JSONObject outUrlJson = new JSONObject();
        // outUrlJson.put("app_id", dyProperty.getAppId()); TODO 注释掉原来的配置死的appid by jjz

        outUrlJson.put("app_id", brandPo.getAppid());// 取品牌绑定的appid
        // outUrlJson.put("path", "/pages/detail/detail?id=" + shopGoodsPo.getId());
        outUrlJson.put("path", "pages/detail/detail");
        JSONObject params = new JSONObject();
        params.put("id", shopGoodsPo.getId());
        params.put("productId", shopGoodsPo.getId());
        outUrlJson.put("params", params.toJSONString());
        saveProductModel.setOut_url(outUrlJson.toJSONString());

        List<SaveProductModel.Poi> pois = /* new ArrayList<>();*/
                poIdList.stream().map(poId -> {
                    SaveProductModel.Poi poi = new SaveProductModel.Poi();
                    poi.setPoi_id(poId);
                    return poi;
                }).collect(Collectors.toList());

        /*  修改品牌多店铺    SaveProductModel.Poi poi = new SaveProductModel.Poi();
        poi.setPoi_id(DyConstant.PO_ID);
        pois.add(poi);*/
        saveProductModel.setPois(pois);

        // 配置商品属性
        productAttrMap.put("trade_url", outUrlJson.toJSONString());
        saveProductModel.setAttr_key_value_map(productAttrMap);

        SaveProductModel.ProductExt productExt = new SaveProductModel.ProductExt();
        productExt.setAgency_rate(100);
        Map<String, Integer> displayPrice = new HashMap<>();
        displayPrice.put("low_price", (int) Math.round(shopGoodsPo.getPrice() * 100));
        displayPrice.put("high_price", (int) Math.round(shopGoodsPo.getPrice() * 100));
        productExt.setDisplay_price(displayPrice);
        productExt.setCategory_out_id(DyConstant.CATEGORY_ID);

        productExt.setAuto_online(true);
        SaveProductModel.TestExtra testExtra = new SaveProductModel.TestExtra();
        // 王显跃 93902594071 黄宇 162347946095880 抖音运营 2705231222148607 李建国 1261862540293195 // 抖音 93348149076
        // TODO 设置测试使用的抖音uid
        testExtra.setUids(
                Arrays.asList("93902594071", "162347946095880", "2705231222148607", "1261862540293195", "93348149076"));
        testExtra.setTest_flag(true);
        // 正式商品
        testExtra.setUids(Collections.emptyList());
        testExtra.setTest_flag(false);
        productExt.setTest_extra(testExtra);
        saveProductModel.setProduct_ext(productExt);

        SaveProductModel.Sku sku = new SaveProductModel.Sku();
        sku.setSku_name(shopGoodsPo.getName());
        sku.setSku_id(shopGoodsPo.getId());
        if (Objects.isNull(shopGoodsPo.getOriPrice())) {
            sku.setOrigin_amount((int) (Math.round(shopGoodsPo.getPrice() * 100)));
        } else {
            sku.setOrigin_amount((int) (Math.round(shopGoodsPo.getOriPrice() * 100)));
        }
        sku.setActual_amount((int) Math.round((shopGoodsPo.getPrice() * 100)));
        SaveProductModel.StockStruct stockStruct = new SaveProductModel.StockStruct();
        stockStruct.setLimit_type(2);
        stockStruct.setStock_qty(100000);
        sku.setStock(stockStruct);
        sku.setOut_sku_id(shopGoodsPo.getId());
        sku.setStatus(1);

        Map<String, String> skuMap = new HashMap<>();
        // "1-抖音码 2-三方码 3-预导码",
        // 抖音码 ：即交易后，抖音发券码，通过抖音侧进行核销，然后同步到开发者。当前仅针对白名单开发者开放。
        // 三方码 ：即交易后，开发者发券码，在开发者侧进行核销，然后核销以及订单状态，同步到抖音。
        // 预导码：可忽略
        skuMap.put("code_source_type", "2");
        // "1-到店核销",默认值
        skuMap.put("use_type", "1");
        // 1-总店结算 2-分店结算 3-区域结算
        skuMap.put("settle_type", "1");
        // 市场价
        if (Objects.isNull(shopGoodsPo.getOriPrice())) {
            skuMap.put("market_price", String.valueOf((int) (shopGoodsPo.getPrice() * 100)));
        } else {
            skuMap.put("market_price", String.valueOf((int) (shopGoodsPo.getOriPrice() * 100)));
        }
        // limit_rule 限制购买
        LimitRuleStruct limitRuleStruct = new LimitRuleStruct();
        limitRuleStruct.setIs_limit(true);
        limitRuleStruct.setTotal_buy_num(200);
        skuMap.put("limit_rule", JSONObject.toJSONString(limitRuleStruct));
        // 商品搭配控件（ItemGroupStruct）
        JSONArray commodityJson = new JSONArray();
        skuMap.put("commodity", commodityJson.toString());
        LimitBuyRuleStruct limitBuyRuleStruct = new LimitBuyRuleStruct();
        skuMap.put("limit_buy_rule", JSONObject.toJSONString(limitBuyRuleStruct));
        sku.setAttr_key_value_map(skuMap);

        SaveDyModel saveDyModel = new SaveDyModel();
        saveDyModel.setProduct(saveProductModel);
        saveDyModel.setSku(sku);
        saveDyModel.setAccount_id(brandPo.getAccountid());
        // saveDyModel.setAccount_id(DyConstant.ACCOUNT_ID); TODO 注释掉原来的配置死的accountid by jjz
        saveDyModel.setAccount_id(brandPo.getAccountid()); // 改成从品牌里面取accountid

        postRequest(DyConstant.SAVE_INFO_POST, saveDyModel, brandPo.getAccountid());

    }

    /**
     * 获取分类
     */
    public String getGoodsType() {
        // 使用 UriComponentsBuilder 构建带参数的 URL
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(DyConstant.GOODS_TYPE_GET)
                .queryParam("account_id", DyConstant.ACCOUNT_ID).queryParam("query_category_type", "1");
        // 创建 HttpHeaders 对象
        return getRequest(builder.toUriString(), DyConstant.ACCOUNT_ID);
    }

    /**
     * 获取商品的模版信息
     */
    public List<ProductAttrs> getProductTemplate(String category_id, String product_type) {

        // 使用 UriComponentsBuilder 构建带参数的 URL
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(DyConstant.GOODS_TEMPLATE_GET)
                .queryParam("category_id", category_id).queryParam("product_type", product_type);

        String result = getRequest(builder.toUriString(), DyConstant.ACCOUNT_ID);
        JSONObject jsonObject = JSONObject.parseObject(result);

        JSONArray productAttrs = jsonObject.getJSONObject("data").getJSONArray("product_attrs");
        return productAttrs.toJavaList(ProductAttrs.class);
    }

    /**
     * 获取商品的草稿 处于新建审核中、修改审核中、或审核成功、失败、商家确认中的数据可以通过该接口查询到
     */
    public List<ProductAttrs> getGoodsDraft(String accountId, String productId) {

        // 使用 UriComponentsBuilder 构建带参数的 URL
        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(DyConstant.GOODS_DRAFT_GET)
                .queryParam("product_ids", productId).queryParam("account_id", accountId);

        String result = getRequest(builder.toUriString(), accountId);
        JSONObject jsonObject = JSONObject.parseObject(result);

        JSONArray productAttrs = jsonObject.getJSONObject("data").getJSONArray("product_attrs");
        return productAttrs.toJavaList(ProductAttrs.class);
    }

    /**
     * 商品id(product_id和out_id至少必填其中一项） 1-上线 2-下线
     */
    public void postOperate(String productId, Integer opType, String accountId) {

        OperateEntity operateEntity = new OperateEntity();
        operateEntity.setProduct_id(productId);
        operateEntity.setOp_type(opType);
        operateEntity.setAccount_id(DyConstant.ACCOUNT_ID);
        String result = postRequest(DyConstant.OPERATE_POST, operateEntity, accountId);
        log.info("===========================================");
        log.info("result is {}", result);
    }

}
